package com.hippy.lib.crash

import android.app.Application
import android.content.Intent
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.os.Build
import android.os.Bundle
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.UnderlineSpan
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.GravityCompat
import kotlinx.android.synthetic.main.activity_crash.*
import java.io.PrintWriter
import java.io.StringWriter
import java.net.InetAddress
import java.net.UnknownHostException
import java.text.SimpleDateFormat
import java.util.*
import java.util.regex.Pattern

class CrashActivity : AppCompatActivity() {
    companion object {
        val CODE_REGEX = Pattern.compile("\\(\\w+\\.\\w+:\\d+\\)")
        fun start(application: Application, throwable: Throwable) {
            if (throwable == null) {
                return
            }
            val intent = Intent(application, CrashActivity::class.java)
            intent.putExtra("other", throwable)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            application.startActivity(intent)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_crash)
        iv_crash_info.setOnClickListener {
            dl_crash_drawer.openDrawer(GravityCompat.START)
        }
        iv_crash_share.setOnClickListener {
            // 分享文本
            val intent = Intent(Intent.ACTION_SEND)
            intent.type = "text/plain"
            intent.putExtra(Intent.EXTRA_TEXT, mStackTrace)
            startActivity(Intent.createChooser(intent, ""))
        }
        iv_crash_restart.setOnClickListener {
            // 重启应用
            RestartActivity.restart(this)
            finish()
        }
        initData()
    }

    private var mStackTrace = ""
    private fun initData() {
        val serializableExtra = intent.getSerializableExtra("other")
        serializableExtra?.let { throwable ->
            if (throwable is Throwable) {
                tv_crash_title.text = throwable.javaClass.simpleName
                val stringWriter = StringWriter()
                val printWriter = PrintWriter(stringWriter)
                throwable.printStackTrace(printWriter)
                val cause = throwable.cause
                cause?.printStackTrace(printWriter)
                mStackTrace = stringWriter.toString()
                val matcher = CODE_REGEX.matcher(mStackTrace)
                val spannable = SpannableStringBuilder(mStackTrace)
                if (spannable.isNotEmpty()) {
                    var index = 0
                    while (matcher.find()) {
                        // 不包含左括号（
                        val start = matcher.start() + "(".length
                        // 不包含右括号 ）
                        val end = matcher.end() - ")".length
                        // 设置前景
                        spannable.setSpan(
                            ForegroundColorSpan(if (index < 3) -0xd78422 else -0x666667),
                            start,
                            end,
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                        )
                        // 设置下划线
                        spannable.setSpan(
                            UnderlineSpan(),
                            start,
                            end,
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                        )
                        index++
                    }
                    tv_crash_message.text = spannable
                }

                val res = resources
                val displayMetrics = res.displayMetrics
                val screenWidth = displayMetrics.widthPixels
                val screenHeight = displayMetrics.heightPixels

                val targetResource: String
                targetResource = if (displayMetrics.densityDpi > 480) {
                    "xxxhdpi"
                } else if (displayMetrics.densityDpi > 320) {
                    "xxhdpi"
                } else if (displayMetrics.densityDpi > 240) {
                    "xhdpi"
                } else if (displayMetrics.densityDpi > 160) {
                    "hdpi"
                } else if (displayMetrics.densityDpi > 120) {
                    "mdpi"
                } else {
                    "ldpi"
                }

                val builder = StringBuilder()
                builder.append("设备品牌：\t").append(Build.BRAND)
                    .append("\n设备型号：\t").append(Build.MODEL)
                    .append("\n设备类型：\t").append(if (isTablet()) "平板" else "手机")

                builder.append("\n屏幕宽高：\t").append(screenWidth).append(" x ").append(screenHeight)
                    .append("\n屏幕密度：\t").append(displayMetrics.densityDpi)
                    .append("\n目标资源：\t").append(targetResource)

                builder.append("\n安卓版本：\t").append(Build.VERSION.RELEASE)
                    .append("\nAPI 版本：\t").append(Build.VERSION.SDK_INT)
                    .append("\nCPU 架构：\t").append(Build.SUPPORTED_ABIS[0])

//                builder.append("\n应用版本：\t")
//                    .append(BuildConfig.VERSION_NAME)
//                    .append("\n版本代码：\t")
//                    .append(AppConfig.getVersionCode())

                try {
                    val dateFormat =
                        SimpleDateFormat("MM-dd HH:mm", Locale.getDefault())
                    val packageInfo = packageManager.getPackageInfo(
                        packageName,
                        PackageManager.GET_PERMISSIONS
                    )
                    builder.append("\n首次安装：\t")
                        .append(dateFormat.format(Date(packageInfo.firstInstallTime)))
                        .append("\n最近安装：\t")
                        .append(dateFormat.format(Date(packageInfo.lastUpdateTime)))
                        .append("\n崩溃时间：\t").append(dateFormat.format(Date()))

                    builder.append("\n当前网络访问：\t")
                    Thread() {
                        kotlin.run {
                            try {
                                InetAddress.getByName("www.baidu.com")
                                builder.append("正常")
                            } catch (ignored: UnknownHostException) {
                                builder.append("异常")
                            }
                            tv_crash_info.post {
                                tv_crash_info.text = builder
                            }
                        }
                    }.start()
                } catch (e: Exception) {

                }

            }
        }
    }

    /**
     * 判断当前设备是否是平板
     */
    private fun isTablet(): Boolean {
        return ((resources.configuration.screenLayout
                and Configuration.SCREENLAYOUT_SIZE_MASK)
                >= Configuration.SCREENLAYOUT_SIZE_LARGE)
    }

    override fun onBackPressed() {
        // 按返回键重启应用
        iv_crash_restart.performClick()
    }
}